﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class TimelineTask : ITimelineTask
{
    private PriorityQueue<TimelineNode> taskQueue = new PriorityQueue<TimelineNode>(new TimelineNodeCmp());
    private float livingTime = 0;
    private float nextTargetTime = Mathf.Infinity;

    public void Init()
    {
        taskQueue = new PriorityQueue<TimelineNode>(new TimelineNodeCmp());
        livingTime = 0;
        nextTargetTime = Mathf.Infinity;
    }

    public void AddTask(float time, Action action)
    {
        TimelineNode node = new TimelineNode(livingTime + time, action);
        taskQueue.Push(node);
        UpdateTargetTime();
    }

    public void UpdateTargetTime()
    {
        var top = taskQueue.Top();
        if (top != null)
        {
            nextTargetTime = top.time;
        }
        else
        {
            nextTargetTime = Mathf.Infinity;
        }
    }

    public void Invoke()
    {
        if (taskQueue.Count > 0)
        {
            var node = taskQueue.Pop();
            node.action.Invoke();
            UpdateTargetTime();
        }
    }

    public void Update()
    {
        ++livingTime;
        if (livingTime > nextTargetTime)
        {
            Invoke();
        }
    }
}
